from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *
from django.http.response import HttpResponse
from .utils import CodeUtils
from captcha.image import ImageCaptcha
from io import BytesIO
import redis


# Create your views here.


r = redis.Redis(host='127.0.0.1', port='6379',password='123', decode_responses=True)


# 校验用户名是否重复
class UniqueUserView(APIView):
    def post(self, request):
        username = request.data.get('username')
        queryset = UserProfile.objects.filter(username=username)
        if queryset:
            return Response({'msg': '用户已存在', 'code': 400})
        else:
            return Response({'msg': '用户名可用', 'code': 200})


# 注册用户
class RegisterView(APIView):
    def post(self, request):
        resp = {}
        key = request.data.get('key')
        img_code = request.data.get('img_code')
        code = r.get(key)
        if code != img_code:
            return Response({'msg': '验证码错误', 'code': 400})
        ser = UserSer(data=request.data)
        if ser.is_valid():
            ser.save()
            resp['msg'] = '注册成功'
            resp['code'] = 200
        else:
            resp['msg'] = '注册失败'
            resp['code'] = 400
            resp['error'] = ser.errors
        return Response(resp)


def make_img_code(request):
    # 1、先生成一个验证码
    code = CodeUtils.mack_code_n(4)
    # 存储 验证码 到某个地方
    # 获取 uuid
    key = request.GET.get('key')
    r.set(key, code, 60)
    # 2、 生成一张图片对象
    image_captcha = ImageCaptcha()
    image = image_captcha.generate_image(code)
    # 创建一个 字节流
    bytes_io = BytesIO()
    image.save(bytes_io, 'jpeg')
    # 返回
    return HttpResponse(bytes_io.getvalue(), content_type='image/jpeg')